package tab;

/*
 AgileLang - A fourth generation language(http://www.agilelang.org).

 Copyright (C) 2013 Roderick Cusirramos (roderick20@hotmail.com)

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import editor.Editor;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rtextarea.RTextScrollPane;
import syntaxtext.SyntaxText;

public class ViewTab extends JTabbedPane {

    Editor frame;

    public ViewTab(Editor frame) {
        super();
        this.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        PanelWelcome panel = new PanelWelcome();
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("editor/bundle/TabBundle_es_PE"); // NOI18N
        
        this.addTab(bundle.getString("start_page"), null, panel);
        EyelashTab pestana = new EyelashTab(this);
        this.setTabComponentAt(getTabCount() - 1, pestana);
    }

    public void addTab(String name) {
        if (this.getSelectedIndex() == -1) {
            SyntaxText editor = new SyntaxText(name);
            editor.setText(opentxt(name));
            this.addTab(name, null, editor.getScrollPane());
            EyelashTab pestana = new EyelashTab(this);
            editor.setEyelash(pestana);
            this.setTabComponentAt(getTabCount() - 1, pestana);
            this.setSelectedIndex(this.getTabCount() - 1);
        } else {
            int end = this.getTabCount();
            for (int i = 0; i < end; i++) {
                EyelashTab pestana = (EyelashTab) getTabComponentAt(i);
                if (name.equals(pestana.path)) {
                    this.setSelectedIndex(i);
                    return;
                }
            }
            SyntaxText editor = new SyntaxText(name);
            editor.setText(opentxt(name));
            this.addTab(name, null, editor.getScrollPane());
            EyelashTab pestana = new EyelashTab(this);
            editor.setEyelash(pestana);
            this.setTabComponentAt(getTabCount() - 1, pestana);
            this.setSelectedIndex(this.getTabCount() - 1);
        }
    }

    public String opentxt(String path) {
        String Text = "", editorfile = "";
        try {
            //FileReader Fichero = new FileReader(path);

            File fileDir = new File(path);
            BufferedReader leer = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(fileDir), "UTF8"));

            //BufferedReader leer = new BufferedReader(Fichero);
            while ((Text = leer.readLine()) != null) {
                editorfile = editorfile + Text + "\n"; //append Concatena la
            }

            leer.close();
            return editorfile;

        } catch (IOException ex) {
            System.out.println("Error reading file ");
            return null;
        }

    }

    public void rename_tab(String name_old, String name_new) {
        if ((new File(name_old)).isFile()) {
            int end = this.getTabCount();
            for (int i = 0; i < end; i++) {
                EyelashTab pestana = (EyelashTab) getTabComponentAt(i);
                if (name_old.equals(pestana.path)) {
                    RTextScrollPane comp2 = (RTextScrollPane) this.getComponentAt(i);
                    JViewport jv = (JViewport) comp2.getComponent(0);
                    RSyntaxTextArea txt = (RSyntaxTextArea) jv.getComponent(0);
                    savetxt(name_old, txt.getText());
                    pestana.path = name_new;
                    this.remove(i);
                    //pestana.updateUI();
                    //this.updateUI();
                    //this.setSelectedIndex(i);
                    return;
                }
            }
        } else {
            //delete(name_old, true);
        }

    }

    public boolean deletefile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return true;
        }

        /*
         * if (!recursive || !file.isDirectory()) { return file.delete();
         }
         */
        if (file.isFile()) {
            int end = this.getTabCount();
            for (int i = 0; i < end; i++) {
                EyelashTab pestana = (EyelashTab) getTabComponentAt(i);
                if (file.getAbsolutePath().equals(pestana.path)) {
                    RTextScrollPane comp2 = (RTextScrollPane) this.getComponentAt(i);
                    JViewport jv = (JViewport) comp2.getComponent(0);
                    RSyntaxTextArea txt = (RSyntaxTextArea) jv.getComponent(0);
                    //savetxt(file.getPath(), txt.getText());
                    //pestana.path = name_new;
                    this.remove(i);
                    //pestana.updateUI();
                    //this.updateUI();
                    //this.setSelectedIndex(i);
                    return true;
                }
            }

        } else {
            removeDirectory(file);
            /*try {
                deleteDirectory(file);
            } catch (IOException ex) {
                Logger.getLogger(ViewTab.class.getName()).log(Level.SEVERE, null, ex);
            }*/
        }

        return file.delete();
    }

  

    public boolean removeDirectory(File directory) {

        // System.out.println("removeDirectory " + directory);
        if (directory == null) {
            return false;
        }
        if (!directory.exists()) {
            return true;
        }
        if (!directory.isDirectory()) {
            return false;
        }

        String[] list = directory.list();

        // Some JVMs return null for File.list() when the
        // directory is empty.
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                File entry = new File(directory, list[i]);

                //        System.out.println("\tremoving entry " + entry);
                if (entry.isDirectory()) {
                    if (!removeDirectory(entry)) {
                        return false;
                    }
                } else {
                    /*if (entry.isFile()) {
                        int end = this.getTabCount();
                        for (int ii = 0; ii < end; ii++) {
                            EyelashTab pestana = (EyelashTab) getTabComponentAt(ii);
                            if (entry.getAbsolutePath().equals(pestana.path)) {
                                RTextScrollPane comp2 = (RTextScrollPane) this.getComponentAt(ii);
                                JViewport jv = (JViewport) comp2.getComponent(0);
                                RSyntaxTextArea txt = (RSyntaxTextArea) jv.getComponent(0);
                                //savetxt(file.getPath(), txt.getText());
                                //pestana.path = name_new;
                                this.remove(ii);
                                //pestana.updateUI();
                                //this.updateUI();
                                //this.setSelectedIndex(i);
                                //return true;
                            }
                        }

                    }*/
                    if (!entry.delete()) {
                        return false;
                    }
                }
            }
        }

        return directory.delete();
    }

    public boolean delete(String filePath, boolean recursive) {
        File file = new File(filePath);
        if (!file.exists()) {
            return true;
        }

        /*
         * if (!recursive || !file.isDirectory()) { return file.delete();
         }
         */
        if (file.isFile()) {
            int end = this.getTabCount();
            for (int i = 0; i < end; i++) {
                EyelashTab pestana = (EyelashTab) getTabComponentAt(i);
                if (file.getName().equals(pestana.path)) {
                    RTextScrollPane comp2 = (RTextScrollPane) this.getComponentAt(i);
                    JViewport jv = (JViewport) comp2.getComponent(0);
                    RSyntaxTextArea txt = (RSyntaxTextArea) jv.getComponent(0);
                    savetxt(file.getPath(), txt.getText());
                    //pestana.path = name_new;
                    this.remove(i);
                    //pestana.updateUI();
                    //this.updateUI();
                    //this.setSelectedIndex(i);
                    return true;
                }
            }

        }

        String[] list = file.list();
        for (int i = 0; i < list.length; i++) {
            if (!delete(filePath + File.separator + list[i], true)) {
                return false;
            }
        }

        return file.delete();
    }

    public void savetxt(String path, String editor) {
        try {
            FileWriter fw = new FileWriter(path);
            fw.write(editor);
            fw.close();
        } catch (IOException e) {
            System.out.println("Can't open file '' for writing");
            return;
        }
    }

    public void newProject() {
        this.removeAll();
    }

    public void openProject() {
        this.removeAll();
    }

    public void closeProject() {
        this.removeAll();
    }

    public void saveAll() {
        int end = this.getTabCount();
        for (int i = 0; i < end; i++) {
            EyelashTab pestana = (EyelashTab) getTabComponentAt(i);
            pestana.save();
            RTextScrollPane comp2 = (RTextScrollPane) this.getComponentAt(i);
            JViewport jv = (JViewport) comp2.getComponent(0);
            RSyntaxTextArea txt = (RSyntaxTextArea) jv.getComponent(0);
            savetxt(pestana.path, txt.getText());
            if (pestana.path.endsWith(".xml") || pestana.path.endsWith(".sql")) {
                this.remove(i);
                i -= 1;
            }

        }
    }
    
    public void closeDelete(){
        int end = this.getTabCount();
            for (int i = 0; i < end; i++) {
                EyelashTab pestana = (EyelashTab) getTabComponentAt(i);
                if (!(new File(pestana.path)).exists()) {
                    this.remove(i);
                    i -= 1;
                }                
            }
    }
}
